package com.dld.coupon.activity;

import java.io.ByteArrayInputStream;

import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Element;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.LinearLayout.LayoutParams;

import com.app.cache.FileUltility;
import com.constant.net.Constant;
import com.dld.android.net.Param;
import com.dld.coupon.util.Common;
import com.dld.protocol.image.DbCache;
import com.dld.protocol.image.ImageProtocol;
import com.dld.protocol.json.Protocol;
import com.json.entity.DlDActivity;
import com.json.entity.ShopDetailBean;

/**
 * http://shenzhen.dld.com/www/?r=www/api/shopDetail&userAgent=dld_android&shopid=(int)
 * 
 * @author Administrator
 * 
 */

public class StoreDetail extends BaseActivity {

	private Protocol ptl;

	private Handler mainhandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			if (msg.what == 0) {
				bindViewByData((ShopDetailBean) msg.obj);
			} else if (msg.what == -1) {
				showException();
			}

		}
	};

	private void binViewItemByAct(int pos, View v, ShopDetailBean sdb) {
		TextView tv1 = (TextView) v.findViewById(R.id.col1);
		TextView tv2 = (TextView) v.findViewById(R.id.col2);
		TextView tv3 = (TextView) v.findViewById(R.id.col3);
		TextView tv4 = (TextView) v.findViewById(R.id.col4);
		if (pos == 0) {
			tv1.setText("优惠项目");
			tv2.setText("原价");
			tv3.setText("小气鬼折扣价");
			tv4.setText("折扣率");
			return;
		}
		if (sdb == null)
			return;
		DlDActivity ac = sdb.getAcs().get(pos - 1);
		tv1.setText(ac.getActive_name() == null ? "无" : ac.getActive_name());
		tv2.setText(ac.getCost_price() == null ? "无" : ac.getCost_price());
		tv3.setText(ac.getCurr_price() == null ? "无" : ac.getCurr_price());
		tv4
				.setText(ac.getDiscount_rate() == null ? "无" : ac
						.getDiscount_rate());

	}

	private void bindViewByData(final ShopDetailBean md) {
		TextView dest = (TextView) findViewById(R.id.coupon_desc_top);
		TextView dest_mid = (TextView) findViewById(R.id.coupon_desc_mid);
		TextView dest_down = (TextView) findViewById(R.id.coupon_desc_down);

		dest.setText(md.getShopname() == null ? "暂无" : md.getShopname());

		dest_mid.setText(md.getAddress() == null ? "" : md.getAddress());

		dest_down.setText(md.getTel() == null ? "暂无" : "电话:" + md.getTel());

		TextView tdes = (TextView) findViewById(R.id.short_desp);
		tdes.setText("   "
				+ (md.getShop_description() == null ? "暂无" : md
						.getShop_description()));

		ImageView imv = (ImageView) findViewById(R.id.logo);
		ImageProtocol ip = new ImageProtocol(this, md.getLogo());
		ip.startTrans(imv);
		ViewGroup vg = (ViewGroup) findViewById(R.id.ac_root);
		vg.removeAllViews();
		for (int i = 0; i < md.getAcs().size() + 1; i++) {
			View v = LayoutInflater.from(this).inflate(R.layout.ac_item, null);
			if (i == 0) {
				v.setBackgroundColor(Color.rgb(0xcc, 0xcc, 0xcc));
			}
			binViewItemByAct(i, v, md);
			vg.addView(v);
		}
		ViewGroup images = (ViewGroup) findViewById(R.id.images_root);
		for (int i = 0; i < md.getImages().size(); i++) {
			final ImageView vimg = new ImageView(this);
			LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(120,
					100);
			lp.weight = 1;
			lp.rightMargin = 2;
			ImageProtocol ipt = new ImageProtocol(this, md.getImages().get(i)
					.getImage());
			final String url = md.getImages().get(i).getImage();
			ipt.startTrans(vimg);
			vimg.setLayoutParams(lp);
			vimg.setDrawingCacheEnabled(true);
			images.addView(vimg);
			vimg.setOnClickListener(new OnClickListener() {

				public void onClick(View v) {

					boolean isDownloaded = DbCache.getInstance(v.getContext())
							.isCached(url);
					if (isDownloaded) {
						ImageView img = new ImageView(v.getContext());
						img.setLayoutParams(new LayoutParams(500, 500));
						String path = FileUltility.converUrlToPath(v
								.getContext(), url);
						Bitmap bmp = BitmapFactory.decodeFile(path);
						img.setImageBitmap(bmp);
						showToastImage(img);
					}
				}

			});

		}
		View map = findViewById(R.id.map_logo);
		// for start google map
		final String lat = "" + Double.parseDouble(md.getX());
		final String lon = "" + Double.parseDouble(md.getY());

		map.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				Common.startGoogleMap(v.getContext(), lon, lat, md
						.getShopname() == null ? "暂无" : md.getShopname());
			};
		});

	}

	private void showToastImage(ImageView img) {

		WindowManager manager = getWindowManager();
		Display display = manager.getDefaultDisplay();
		int width = display.getWidth();
		int height = display.getHeight();

		final AlertDialog alert = new AlertDialog.Builder(this).create();
		alert.show();

		alert.getWindow().setLayout(width * 2 / 3, height * 2 / 3);
		alert.getWindow().setContentView(img);
		img.setOnClickListener(new View.OnClickListener() {

			public void onClick(View v) {
				Log.v("", "*** *************   onclick  ");
				alert.dismiss();
			}

		});

	}

	@Override
	protected void onCreate(Bundle paramBundle) {
		super.onCreate(paramBundle);
		setContentView(R.layout.store_detail_2012);
		init();
		initSegment();

	}

	private void init() {
		String disid = getIntent().getExtras().getString(
				Constant.CONSTANT_SHOPID);
		Param p = new Param();
		p.append("r", "www/api/shopDetail");
		p.append("userAgent", "dld_android");
		p.append("shopid", disid);
		ptl = new Protocol(p);
		ptl.startTrans(new MyRetResult());

	}

	private void showException() {
		AlertDialog.Builder adb = new AlertDialog.Builder(this);
		final AlertDialog ad = adb.create();
		ad.setTitle("网络异常");
		ad.setMessage("网络异常，请重试");
		ad.setButton("确定", new DialogInterface.OnClickListener() {

			public void onClick(DialogInterface dialog, int which) {
				init();
				ad.dismiss();
			}
		});

		ad.setButton2("取消", new DialogInterface.OnClickListener() {

			public void onClick(DialogInterface dialog, int which) {
				ad.dismiss();
			}

		});
		ad.show();
	}

	private class MyRetResult extends Protocol.OnJsonProtocolResult {

		public MyRetResult() {
			super(String.class);
		}

		@Override
		public void onException(String paramString, Exception paramException) {
			mainhandler.sendMessage(Message.obtain(mainhandler, -1));
		}

		@Override
		public void onResult(String paramString, Object paramObject) {
			String content = (String) paramObject;
			try {
				Element root = DocumentBuilderFactory.newInstance()
						.newDocumentBuilder().parse(
								new ByteArrayInputStream(content.getBytes()))
						.getDocumentElement();
				ShopDetailBean md = ShopDetailBean.fromElement(root);
				Log.v("", "*****************  shop detail bean   "
						+ md.getImages().size());
				mainhandler.sendMessage(Message.obtain(mainhandler, 0, md));
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

	}

}
